<template>
  <el-scrollbar
    ref="scrollContainerRef"
    @scroll="onScroll"
  >
    <slot />
  </el-scrollbar>
</template>
<script lang="ts" setup name="ScrollPane">
import { ref } from 'vue';

import type { ElScrollbar } from 'hive-plus';

type ScrollValue ={
  scrollLeft: number,
  scrollTop: number
}

const scrollLeft = ref(0);
const scrollContainerRef = ref<InstanceType<typeof ElScrollbar>>();

const onScroll = (value: ScrollValue) => {
  scrollLeft.value = value.scrollLeft;
};

/**
 * @description: 父组件调用
 * @param {*} curTag 当前的导航标签
 * @param {*} tagList 所有导航标签列表
 * @param {*} scrollPaneWidth
 * @return {*}
 */
const moveToCurrentTag = (curTag:HTMLElement, tagList:Array<HTMLElement>, scrollPaneWidth:number) => {
  let firstTag = null;
  let lastTag = null;

  if (tagList && tagList.length > 0) {
    firstTag = tagList[0];
    lastTag = tagList[tagList.length - 1];
  }

  if (firstTag === curTag) {
    scrollContainerRef.value?.setScrollLeft(0);
  } else if (lastTag === curTag) {
    const allTagsOffsetWidth = [...tagList].reduce((pre, next) => pre + next.offsetWidth, 0);
    const scrollLeftWidth = allTagsOffsetWidth - scrollPaneWidth + lastTag.offsetWidth;
    scrollContainerRef.value?.setScrollLeft(scrollLeftWidth);
  } else {
    // 获取到当前标签的上一个和下一个标签
    const curIndex = [...tagList].findIndex((item) => item === curTag);
    const prevTag:TypeObject = tagList[curIndex - 1];
    const nextTag:TypeObject = tagList[curIndex + 1];

    const beforePrevTagOffsetLeft = prevTag.offsetLeft - prevTag.offsetWidth;
    const afterNextTagOffsetLeft = nextTag.offsetLeft + nextTag.offsetWidth;

    if (afterNextTagOffsetLeft > (scrollLeft.value + scrollPaneWidth)) {
      scrollContainerRef.value?.setScrollLeft(afterNextTagOffsetLeft - scrollPaneWidth);
    } else if (beforePrevTagOffsetLeft < scrollLeft.value) {
      scrollContainerRef.value?.setScrollLeft(beforePrevTagOffsetLeft);
    }
  }
};

defineExpose({
  moveToCurrentTag
});
</script>

<style lang="scss" scoped>
:deep(.#{$namespace}-scrollbar) {
  position: relative;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
}

:deep(.#{$namespace}-scrollbar__wrap) {
  overflow-y: hidden !important;
}

:deep(.#{$namespace}-scrollbar__bar) {
  display: none !important;
  opacity: 0 !important;
}
</style>
